package com.market.cash.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.market.cash.R
import com.market.cash.databinding.CashVerificationBinding
import com.market.cash.pro.ProActivity
import com.market.cash.ui.presenter.CashRootVerificationPresenter
import com.market.cash.ui.view.ICashRootVerificationView
import com.market.cash.utils.CashRootBarUtil
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.CashRootProcessHelper
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.utils.log.CashRootLog
import com.market.cash.utils.sms.CashRootSMSBroadcastReceiver
import com.market.cash.utils.thread.TimingThread

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/24 16:41
 * @Annotation：账号验证页面
 */
class VerificationActivity: ProActivity(), ICashRootVerificationView,TimingThread.ITimingThreadListener {
    lateinit var binding: CashVerificationBinding
    var presenter: CashRootVerificationPresenter? = null
    val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    private var timeThread: TimingThread? = null
    //等待时长
    private var countdown = 60

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, VerificationActivity::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }
    override fun getCashRootRootView(): View? {
        binding = CashVerificationBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        CashRootBarUtil.setStatusBarLightMode(this, false)
        binding.titleBarLayout.setPadding(0, CashRootBarUtil.getStatusBarHeight(),0,0)
        initCashRootRefreshLayout()

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initCashRootListener() {
        //客服
        binding.imgKefu.setOnClickListener {
            KefuActivity.start(this,eventRemark,loadPName(),loadPToken())
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,eventRemark)
        }
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnContinue.isEnabled = presenter!!.getSelectType().isNotEmpty() && binding.editCode.text.toString().isNotEmpty()
            }
        })

        //SMS
        binding.smsLayout.setOnClickListener {
            presenter!!.checkCashRootVerificationType("SMS")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_VERIFICATION_SMS)
        }

        //WhatsApp
        binding.whatsappLayout.setOnClickListener {
            presenter!!.checkCashRootVerificationType("WHATSAPP")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_VERIFICATION_WHATSAPP)
        }

        binding.btnContinue.setOnClickListener {
            presenter!!.onCashRootVerificationCodeAction(binding.editCode.text.toString())
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_VERIFICATION_CONTINUE)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initCashRootData() {
        presenter = CashRootVerificationPresenter(this)
        val zoneCode = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_TIMEZONE_CODE)
        val mobile = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_MOBILE)
        binding.textMobile.text = "+$zoneCode $mobile"

        binding.textCountdown.visibility = View.GONE
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true

        binding.smsLayout.visibility = View.GONE
        binding.whatsappLayout.visibility = View.GONE
        if (CashRootProcessHelper.isCheckSMS()){
            binding.smsLayout.visibility = View.VISIBLE
        }
        if (CashRootProcessHelper.isCheckWhatsApp()){
            binding.whatsappLayout.visibility = View.VISIBLE
        }

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        val testSMSReceiver = CashRootSMSBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(
                testSMSReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null,
                Context.RECEIVER_EXPORTED // 指定导出标志
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(
                testSMSReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null
            )
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(
                testSMSReceiver,
                intentFilter
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                CashRootLog.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                CashRootLog.e("Sms code: $code")
                if (code != null){
                    binding.editCode.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                CashRootLog.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initCashRootRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PROCESS_REFRESH))
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 获取查看的产品名称
     */
    override fun loadPName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun loadPToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 切换校验类型
     */
    override fun showCashRootVerificationType(type: String) {
        binding.imgSelectSms.setImageResource(R.mipmap.cash_verification_normal)
        binding.imgSelectWhatsApp.setImageResource(R.mipmap.cash_verification_normal)
        when(type){
            "SMS" -> {
                binding.imgSelectSms.setImageResource(R.mipmap.cash_verification_select)
            }
            else -> {
                binding.imgSelectWhatsApp.setImageResource(R.mipmap.cash_verification_select)
            }
        }
        binding.btnContinue.isEnabled = binding.editCode.text.toString().isNotEmpty()
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    override fun showCashRootSendCodeSuccess(directLoginFlag: String) {
        hideCashRootLoading()
        when(directLoginFlag){
            "YES" -> {
                showCashRootVerificationSuccess()
            }
            else -> {
                startTimeThread()
            }
        }
    }

    /**
     * 校验成功
     */
    override fun showCashRootVerificationSuccess() {
        publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PROCESS_REFRESH))
        finish()
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        //随机 60秒 等待时长
        countdown = 59
        binding.textCountdown.text = "${countdown}s"
        binding.textCountdown.visibility = View.VISIBLE
        binding.smsLayout.isEnabled = false
        binding.whatsappLayout.isEnabled = false
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    @SuppressLint("SetTextI18n")
    override fun onLoading() {
        if (countdown <= 0){
            countdown = 60
            timeThread!!.stopThread()
            binding.textCountdown.visibility = View.GONE
            binding.smsLayout.isEnabled = true
            binding.whatsappLayout.isEnabled = true
            return
        }
        countdown--
        binding.textCountdown.text = "${countdown}s"
    }

    override fun onCashRootEvent(event: CashRootEventData) {
        super.onCashRootEvent(event)
        when(event.eventType){
            CashRootEventData.TYPE.CASHROOT_PROCESS_REFRESHED -> {
                hideCashRootLoading()
                //需要校验 WhatsApp 或 SMS
                if (!CashRootProcessHelper.isCheckWhatsApp() && !CashRootProcessHelper.isCheckSMS()){
                    //校验成功
                    showCashRootVerificationSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun hideCashRootLoading() {
        super.hideCashRootLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${loadPName()} Verification Page"
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_VERIFICATION_SMS_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_VERIFICATION_SMS_END, eventRemark)
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
    }
}